export const add = (db: any, dbName: string, data: any) => {
  var request = db
    .transaction([dbName], "readwrite") //新建事务，readwrite, readonly(默认), versionchange
    .objectStore(dbName) //拿到IDBObjectStore 对象
    .add(data);
  request.onsuccess = function (success: any) {
    console.log("数据写入成功", success.type);
  };
  request.onerror = function (err: any) {
    console.log("数据写入失败", err.target.error.message);
  };
  request.onabort = function () {
    console.log("事务回滚");
  };
};

export const getByKey = (db: any, dbName: string, hash: string) => {
  return new Promise<any>((resolve, reject) => {
    var transaction = db.transaction([dbName]);
    var objectStore = transaction.objectStore(dbName);
    var index = objectStore.index("hash");
    var req = index.get(hash);
    req.onsuccess = function (e: any) {
      var result = e.target.result;
      if (result) {
        resolve(result);
      } else {
        reject("无此数据");
        console.log("无此数据");
      }
    };
  });
};
export const get = (db: any, dbName: string, key: string | number) => {
  return new Promise<any>((resolve, reject) => {
    var transaction = db.transaction([dbName]);
    var objectStore = transaction.objectStore(dbName);
    var request = objectStore.get(key); //传主键
    request.onerror = function () {
      console.log("事务失败");
      reject("获取事务失败");
    };
    request.onsuccess = function () {
      if (request.result) {
        resolve(request.result);
      } else {
        resolve(null);
        console.log("未获得数据记录");
      }
    };
  });
};
// function update() {
//   var request = db.value.transaction(['fileBase64'], 'readwrite').objectStore('fileBase64').put({
//     hash: 1,
//     name: '书剑恩仇录2',
//   });
//   request.onsuccess = function () {
//     console.log('数据更新成功');
//   }
//   request.onerror = function () {
//     console.log('数据更新失败');
//   }
// }

// function remove() {
//   var request = db.value.transaction(['fileBase64'], 'readwrite')
//     .objectStore('fileBase64')
//     .delete(1);
//   request.onsuccess = function () {
//     console.log('数据删除成功');
//   };
// }
// function clear() {
//   var request = db.value.transaction(['fileBase64'], 'readwrite')
//     .objectStore('fileBase64')
//     .clear();
//   request.onsuccess = function () {
//     console.log('数据清除成功');
//   };
// }